import { Component, createRef } from "react";

/**
 *  1、获取父组件传递的值从this.props中获取
 *  2、定义state = {} 为数据仓库。通过this.state来访问
 *  3、更改state要使用this.setState()。只会修改设置的属性。修改深层属性时仍需要解构（全量修改）
 *  4、获取dom对象，使用createRef()方法定义，绑定在元素的ref属性上
 *      - 类似于函数组件的useRef()
 */

class User extends Component {
  state = {
    number: 0,
    text: "哈哈哈哈",
    people: { name: "孙悟空", age: 19 },
  };

  // 函数都应该以箭头函数定义，避免this为undefined
  addNumber = () => {
    // console.log(this);
    this.setState({ number: this.state.number + 1 });
    // this.setState((prevState) => {
    //   console.log(prevState);
    //   return {
    //     number: prevState.number + 1,
    //   };
    // });
  };
  changePeople = () => {
    // 这里需要对people全量修改，否则数据会丢失
    this.setState({ people: { ...this.state.people, age: 20 } });
  };

  // 获取dom对象
  divRef = createRef();
  getDom = () => {
    const { current } = this.divRef;
    console.log("dom对象:", this.divRef);
    console.log("current:", current);
  };
  render() {
    // console.log(this.props);
    return (
      <div ref={this.divRef}>
        <h4>{this.state.number}</h4>
        <h3>{this.state.text}</h3>
        <button onClick={this.addNumber}>加1</button>
        <hr></hr>
        <h4>
          {this.state.people.name}--{this.state.people.age}
        </h4>
        <button onClick={this.changePeople}>改年龄</button>
        <hr></hr>
        <button onClick={this.getDom}>获取dom对象</button>
        <hr></hr>
        <ul>
          <li>姓名：{this.props.name}</li>
          <li>年龄：{this.props.age}</li>
          <li>性别：{this.props.sex}</li>
        </ul>
      </div>
    );
  }
}
export default User;
